/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.carpark.dao;

import cz.muni.fi.pa165.carpark.entities.User;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Martin
 */
@Repository
public class UserDAOImpl implements UserDAO {

    @PersistenceContext
    private EntityManager em;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        TypedQuery<User> query = em.createQuery("SELECT u FROM User u WHERE u.userName = :name", User.class);
        query.setParameter("name", name);
        User result = null;
        try {
            result = query.getSingleResult();
        } catch (NoResultException e) {
            throw new UsernameNotFoundException("User with username " + name + " does not exist");
        }
        return result;
    }

    public void setEntityManager(EntityManager em) {
        this.em = em;
    }
    
    @Override
    public void create(User u) {
        if(u.getId() != null) {
            throw new IllegalArgumentException("User already has some ID");
        }
        try {
            this.loadUserByUsername(u.getUserName());
            // user exists, usually, an exception would be thrown, but we do not care
        } catch (UsernameNotFoundException e) {
            em.persist(u);
        }
    }
    
    
}
